<template>
  <view class="content">
    <ZPaging
      ref="paging"
      v-model="list"
      :auto="false"
      :auto-show-system-loading="true"
      system-loading-text="Loading"
      loading-more-no-more-text="沒有更多了"
      loading-more-default-text="點擊加載更多"
      loading-more-loading-text="正在加載..."
      loading-more-fail-text="加載失敗,點擊重新加載"
      empty-view-text="沒有數據哦~"
      refresher-default-text="繼續下拉刷新"
      refresher-pulling-text="鬆開立即刷新"
      refresher-refreshing-text="正在刷新"
      empty-view-reload-text="重新加載"
      empty-view-error-text="加載失敗"
      @query="queryList"
    >
      <template #top>
        <NavBar :title="title" :autoBack="false" id="nav">
          <template #right>
            <view
              class="new_form"
              v-if="userinfo.ident === 1"
              @click="toPage('CheckForm')"
            >
              檢查表庫
            </view>
            <view
              v-if="userinfo.ident === 1"
              class="navbar-right center"
              @click="showSelectCompany"
            >
              <u-icon
                class="ml-20"
                name="plus"
                color="#007aff"
                size="34"
              ></u-icon>
            </view>
          </template>
        </NavBar>
      </template>
      <template #default>
        <view class="list">
          <view class="listitem">
            <view v-for="(v, k) in list" :key="k">
              <u-swipe-action
                v-if="v.cmident == 1|| v.cmident == 2"
                :show="v.show"
                :index="k"
                bg-color="#fff"
                :options="getOptions(v)"
                :disabled="v.disabled"
                @open="open"
                @click="swipeAction"
              >
                <view class="item" @click.stop="toPage('Step', { id: v.id })">
                  <view class="flex title">
                    <text class="f36 bold">{{ v.title }}</text>
                    <text class="f26 c333" v-if="v.inputtime != 0"
                      >交件日期:{{ v.inputtime }}</text
                    >
                  </view>
                  <view class="flex time" v-if="v.start && v.end">
                    <view class="left"
                      >{{ v.start }}~{{
                        v.delay == 0 ? v.end : v.showendtime
                      }}</view
                    >
                    <view class="f24 right" v-if="v.delay > 0"
                      >延遲{{ v.delay }}天</view
                    >
                    <view class="f24 right" v-if="v.delay < 0"
                      >提前{{ Math.abs(v.delay) }}天</view
                    >
                  </view>
                  <view class="company">
                    {{ v.name }}
                  </view>
                  <view class="flex memlist">
                    <view class="ml">
                      <view class="start row1">
                        <view class="f26 label">desingers:</view>
                        <view class="start val">
                          <text
                            class="txt f26"
                            v-for="(dv, dk) in v.desingers"
                            :key="dk"
                            >{{ dv }}</text
                          >
                          <!-- <text class="txt f26" v-for="(mv,mk) in v.managers" :key="mk">{{mv}}</text> -->
                        </view>
                      </view>
                      <view class="start row1">
                        <view class="f26 label">clients:</view>
                        <view class="start val">
                          <text
                            class="txt f26"
                            v-for="(cv, ck) in v.clients"
                            :key="ck"
                            >{{ cv }}</text
                          >
                        </view>
                      </view>
                    </view>
                    <view
                      class="center cfff f26 mr"
                      v-if="v.cmident === 1"
                      @click.stop="toUserpage(v.id)"
                    >
                      管理人員
                    </view>
                  </view>
                  <view class="progress">
                    <view class="start items">
                      <view class="label">實際進度</view>
                      <view class="flex val">
                        <view class="pro">
                          <u-line-progress
                            :show-percent="false"
                            height="8"
                            active-color="#007aff"
                            inactive-color="#fac42e"
                            :percent="v.progress"
                          ></u-line-progress>
                        </view>
                        <text class="end txt f26">{{ v.progress }}%</text>
                      </view>
                    </view>
                    <view class="start items">
                      <view class="label">預期進度</view>
                      <view class="flex val">
                        <view class="pro">
                          <u-line-progress
                            :show-percent="false"
                            height="8"
                            active-color="#007aff"
                            :percent="+v.progress_plan"
                          ></u-line-progress>
                        </view>
                        <text class="end txt f26">{{ v.progress_plan }}%</text>
                      </view>
                    </view>
                  </view>
                  <view class="mb-10 price" @click.stop="toPage('CostDetails', { id: v.id })">
                    執行預算：<text class="colorB">{{ v.getprice }}/{{ v.price }}</text>
                  </view>
                  <view class="end ac btns">
                    <!-- <a v-if="v.pdf && isPc" :href="v.pdf" target="downloadFile" download>{{v.title}}.pdf</a> -->
                    <view class="btn">
                      <view class="c007aff" @click.stop="downLoadExcel(v.id)"
                        >導出Excel</view
                      >
                    </view>
                    <view class="btn">
                      <view class="c007aff" @click.stop="copyProject(v.id)"
                        >復製項目</view
                      >
                    </view>
                    <view class="btn">
                      <view class="c007aff" @click.stop="getpdfpage(v.id)"
                        >生成pdf</view
                      >
                    </view>
                    <!-- <a class="btn" v-if="isPc" :href="v.pdf">查看PDF</a> -->
                    <view
                      class="btn c007aff"
                      v-if="v.pdf"
                      @click.stop="copyPdfPath(v.pdf)"
                      >查看PDF</view
                    >
                    <view
                      class="btn c007aff"
                      @click.stop="toPage('Casedata', { id: v.id })"
                      >專案資料</view
                    >
                  </view>
                </view>
              </u-swipe-action>

              <view
                class="item"
                v-else
                @click.stop="toPage('Step', { id: v.id })"
              >
                <view class="flex title">
                  <text class="f36 bold">{{ v.title }}</text>
                  <text class="f26 c333" v-if="v.inputtime != 0"
                    >交件日期:{{ v.inputtime }}</text
                  >
                </view>
                <view class="flex time" v-if="v.start && v.end">
                  <view class="left"
                    >{{ v.start }}~{{
                      v.delay == 0 ? v.end : v.showendtime
                    }}</view
                  >
                  <view class="f24 right" v-if="v.delay > 0"
                    >延遲{{ v.delay }}天</view
                  >
                  <view class="f24 right" v-if="v.delay < 0"
                    >提前{{ Math.abs(v.delay) }}天</view
                  >
                </view>
                <view class="company">
                  {{ v.name }}
                </view>
                <view class="flex memlist">
                  <view class="ml">
                    <view class="start row1">
                      <view class="f26 label">desingers:</view>
                      <view class="start val">
                        <text
                          class="txt f26"
                          v-for="(dv, dk) in v.desingers"
                          :key="dk"
                          >{{ dv }}</text
                        >
                        <!-- <text class="txt f26" v-for="(mv,mk) in v.managers" :key="mk">{{mv}}</text> -->
                      </view>
                    </view>
                    <view class="start row1">
                      <view class="f26 label">clients:</view>
                      <view class="start val">
                        <text
                          class="txt f26"
                          v-for="(cv, ck) in v.clients"
                          :key="ck"
                          >{{ cv }}</text
                        >
                      </view>
                    </view>
                  </view>
                  <view
                    class="center cfff f26 mr"
                    v-if="v.cmident === 1"
                    @click.stop="toUserpage(v.id)"
                  >
                    管理人員
                  </view>
                </view>
                <view class="progress">
                  <view class="start items">
                    <view class="label">實際進度</view>
                    <view class="flex val">
                      <view class="pro">
                        <u-line-progress
                          :show-percent="false"
                          height="8"
                          active-color="#007aff"
                          inactive-color="#fac42e"
                          :percent="v.progress"
                        ></u-line-progress>
                      </view>
                      <text class="end txt f26">{{ v.progress }}%</text>
                    </view>
                  </view>
                  <view class="start items">
                    <view class="label">預期進度</view>
                    <view class="flex val">
                      <view class="pro">
                        <u-line-progress
                          :show-percent="false"
                          height="8"
                          active-color="#007aff"
                          :percent="+v.progress_plan"
                        ></u-line-progress>
                      </view>
                      <text class="end txt f26">{{ v.progress_plan }}%</text>
                    </view>
                  </view>
                </view>
                <view class="mb-10 price" @click.stop="toPage('CostDetails', { id: v.id })">
                  執行預算：<text class="colorB">{{ v.getprice }}/{{ v.price }}</text>
                </view>
                <view class="end ac btns">
                  <view class="btn" v-if="v.cmident === 1 || v.cmident === 2">
                      <view class="c007aff" @click.stop="downLoadExcel(v.id)"
                        >導出Excel</view
                      >
                    </view>
                    <view class="btn" v-if="v.cmident === 1 || v.cmident === 2">
                      <view class="c007aff" @click.stop="copyProject(v.id)"
                        >復製項目</view
                      >
                    </view>
                  <view class="btn" v-if="v.cmident == 1 || v.cmident === 2">
                    <view class="c007aff" @click.stop="getpdfpage(v.id)"
                      >生成pdf</view
                    >
                  </view>
                  <view
                    class="btn c007aff"
                    v-if="v.pdf"
                    @click.stop="copyPdfPath(v.pdf)"
                    >查看PDF</view
                  >
                  <view
                    class="btn c007aff"
                    v-if="v.cmident === 1 || v.cmident === 2"
                    @click.stop="toPage('Casedata', { id: v.id })"
                    >專案資料</view
                  >
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
    </ZPaging>
    <u-picker
      mode="selector"
      v-model="showCompany"
      range-key="name"
      :range="companyList"
      @confirm="selectCompany"
      confirm-text="確認"
      :default-selector="[companyIndex]"
    ></u-picker>

    <!-- 刪除 -->
    <u-modal
      v-model="delshow"
      :mask-close-able="true"
      :show-cancel-button="true"
      title="確認刪除專案嗎？"
      content="將會刪除該專案下的所有數據,刪除后不可恢復"
      @confirm="delCaseById"
    ></u-modal>
    <Tabar></Tabar>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import {
  getCompanyByUserEmail,
  getCaselist,
  delCase,
  getPdf,
  copyCase,
  downloadExcel,
} from '@/api/apis.js'
import NavBar from '@/component/NavBar'
import Tabar from '@/component/HomeTab'
import ZPaging from '@/node_modules/z-paging/components/z-paging/z-paging.vue'
import { get } from 'lodash'
export default {
  components: {
    NavBar,
    ZPaging,
    Tabar,
  },
  data() {
    return {
      isPc: null,
      title: '專案列表',
      list: [],
      delshow: false,
      delId: 0,
      companyList: [],
      showCompany: false,
      companyIndex: 0,
      curCompany: {},
      options: [
        {
          text: 'Edit',
          style: {
            backgroundColor: '#ccc',
            color: '#fff',
          },
        },
        {
          text: 'Delete',
          style: {
            backgroundColor: '#ff0000',
            color: '#fff',
          },
        },
      ],
    }
  },
  onShow() {
    const app = getApp()
    this.isPc = app.globalData.isPc
    uni.setStorageSync('tabIndex', 0)
    // console.log("this",this.ismobile)
    this.setTabList(uni.getStorageSync('bindevice'))
    this.$nextTick(() => {
      if (uni.getStorageSync('islogin')) {
        this.changeUserIdent(uni.getStorageSync('ident'))
        this.changeUserName(uni.getStorageSync('name'))
        this.reload()
        this.init()
      } else {
        this.$Toast('請先登錄')
        setTimeout(() => {
          this.toPage('Home')
        }, 1200)
      }
    })
  },
  mounted() {
    this.previousWidth = window.innerWidth
    this.previousHeight = window.innerHeight
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  onLoad() {},

  computed: {
    ...mapState(['userinfo']),
  },
  methods: {
    ...mapMutations([
      'chageUserPageType',
      'chageUserPageId',
      'changeUserIdent',
      'changeUserName',
      'setTabList',
    ]),
    init() {
      let uid = uni.getStorageSync('uid')
      getCompanyByUserEmail({ uid })
        .then((res) => {
          this.companyList = res
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    getOptions(v) {
      let options = [{
          text: 'Edit',
          style: {
            backgroundColor: '#ccc',
            color: '#fff',
          },
        },
        {
          text: 'Delete',
          style: {
            backgroundColor: '#ff0000',
            color: '#fff',
          },
        },
      ]
      if (v.cmident == 1) {
        return options
      } else if (v.cmident == 2) {
        options = [{
          text: 'Edit',
          style: {
            backgroundColor: '#ccc',
            color: '#fff',
          },
        },
      ]
      } else {
        options  = []
      }
      return options
    },
    handleResize() {
      const currentWidth = window.innerWidth
      const currentHeight = window.innerHeight
      const swipeViews = document.querySelectorAll('.u-swipe-view')
      swipeViews.forEach((swipeView) => {
        swipeView.style.width = `calc(100% + 180px)`
      })
    },
    loginout() {
      uni.removeStorageSync('uid')
      uni.removeStorageSync('userToken')
      uni.removeStorageSync('ident')
      uni.removeStorageSync('islogin')
      uni.removeStorageSync('name')
      uni.removeStorageSync('tabIndex')
      uni.removeStorageSync('caseid')
      uni.removeStorageSync('fileDir')
      this.$Toast('退出成功')
      setTimeout(() => {
        //跳轉到登錄頁
        this.$navi({
          route: {
            name: 'Home',
          },
        })
      }, 1200)
    },
    copyProject(id) {
      let uid = uni.getStorageSync('uid')
      let data = {
        uid,
        id,
      }
      this.$Toast('生成中')
      copyCase(data)
        .then((res) => {
          setTimeout(() => {
            uni.hideLoading()
            this.reload()
          }, 1000)
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    downLoadExcel(id) {
      let uid = uni.getStorageSync('uid')
      let data = {
        uid,
        id,
      }
      this.$Toast('下載中')
      downloadExcel(data)
        .then((res) => {
          uni.hideLoading()
          if (res && res.url) {
            let url = res.url
            let nameArr = url.split('/')
            let fileName = nameArr[nameArr.length - 1]
            const tempLink = document.createElement('a')
            tempLink.style.display = 'none'
            tempLink.href = url
            tempLink.setAttribute('download', fileName)
            tempLink.setAttribute('target', '_blank')
            document.body.appendChild(tempLink)
            tempLink.click()
            document.body.removeChild(tempLink)
          }
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    getpdfpage(caseid) {
      let uid = uni.getStorageSync('uid')
      let data = {
        uid,
        caseid,
      }
      this.$Toast('生成中')
      getPdf(data)
        .then((res) => {
          setTimeout(() => {
            uni.hideLoading()
            this.reload()
          }, 1000)
          // this.$Toast("下載中")
          // uni.downloadFile({
          // 	url: res.url, //仅为示例，并非真实的资源
          // 	success: (result) => {
          // 		//保存文件
          // 		// uni.saveFile({
          // 		// 	tempFilePath: result.tempFilePath,
          // 		// 	success: (saveRes) => {
          // 		// 		console.log('Download successful');
          // 		// 		console.log('File saved at: ' + saveRes.savedFilePath);
          // 		// 	},
          // 		// 	fail: (saveErr) => {
          // 		// 		console.log('Failed to save file:', saveErr);
          // 		// 	}
          // 		// });

          // 	},
          // 	fail:(err)=>{
          // 		console.log("err",err)
          // 	}
          // });
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    copyPdfPath(path) {
      let _this = this
      uni.setClipboardData({
        data: path,
        success: function () {
          _this.$Toast('复制成功')
        },
        fail: function (err) {
          _this.$Toast('复制失败')
        },
      })
      this.toPage('Pdf', { path })
    },
    toUserpage(id) {
      this.chageUserPageType('admin')
      this.chageUserPageId(id)
      uni.setStorageSync('caseid', id)
      this.toPage('Contacts', { type: 'admin', id: id })
    },
    swipeAction(index, subindex) {
      if (subindex === 0) {
        //to edit
        this.toPage('AddTask', {
          type: 'case',
          model: 'edit',
          id: this.list[index].id,
        })
      } else {
        //to delete
        this.delId = this.list[index].id
        this.delshow = true
      }
    },
    open(index) {
      this.list[index].show = true
      this.list.map((v, k) => {
        if (index != k) this.list[k].show = false
      })
    },
    delCaseById() {
      if (this.delId <= 0) {
        return false
      }
      let data = {
        id: this.delId,
        uid: uni.getStorageSync('uid'),
      }
      delCase(data)
        .then((res) => {
          this.$Toast(res.msg)
          setTimeout(() => {
            this.reload()
          }, 1200)
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    selectCompany(e) {
      this.companyIndex = e[0]
      this.curCompany = this.companyList[e]
      this.toPage('AddTask', { type: 'case', item: this.curCompany })
    },
    queryList(pageNo, pageSize) {
      let data = {
        pageNo,
        pageSize,
        uid: uni.getStorageSync('uid'),
      }
      getCaselist(data)
        .then((res) => {
          this.$refs.paging.complete(res)
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    showSelectCompany() {
      this.showCompany = true
    },
    reload() {
      this.$refs.paging.reload()
    },
    toPage(name, params = {}) {
      this.$navi({
        route: {
          name,
          params,
        },
      })
    },
  },
}
</script>

<style lang="scss">
.content {
  min-height: 100vh;
  max-width: 750px;
  margin: 0 auto;
  padding-bottom: 40rpx;
}

.list {
  width: 100%;
  padding-top: 88rpx;
  // background-color: #ffd33b;
  // padding-bottom: 40rpx;
  // padding-left: 30rpx;
  /deep/ .u-btn-text {
    color: #fff !important;
  }
  .item {
    // padding: 10rpx 0 40rpx;
    // margin-top: 50rpx;
    // padding-right: 30rpx;
    // padding-bottom: 20rpx;
    background-color: #ffd33b;
    padding: 40rpx 30rpx;
    margin-bottom: 10rpx;
    .time {
      padding: 6rpx 0;
    }
    .company {
      padding: 6rpx 0;
    }
    .memlist {
      padding: 10rpx 0;
      .ml {
        width: calc(100% - 180rpx);
        margin-right: 20rpx;
        .row1 {
          margin: 4rpx 0;
        }
        .val {
          flex-wrap: wrap;
          .txt {
            padding: 0 10rpx;
          }
        }
      }
      .mr {
        flex-shrink: 0;
        width: 160rpx;
        height: 70rpx;
        background-color: #007aff;
        border-radius: 10rpx;
        box-shadow: 2rpx 2rpx 6rpx rgba(9, 100, 199, 1);
      }
    }
    .progress {
      .items {
        padding: 4rpx 0;
        .label {
          width: 120rpx;
          margin-right: 20rpx;
        }
        .val {
          width: calc(100% - 300rpx);
          align-items: center;
          .pro {
            width: calc(100% - 90rpx);
            // width: 100%;
          }
          .txt {
            width: 80rpx;
          }
        }
      }
    }
    .price {
      padding: 4rpx 0;
    }
    .ac {
      text-align: right;
      
    }
		.btns{
			.btn {
        text-decoration: none;
        margin-left: 12rpx;

      }
		}
  }
}
.colorB{
  color: #007aff;
}
</style>
